﻿using IntelligentGateway.Model;
using IntelligentGateway.Model.Panel;
using IntelligentGateway.Services;
using IntelligentGateway.Services.Panel;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace IntelligentGateway.Controllers.api
{
    [Route("api/[controller]")]
    [ApiController]
    public class PanelController : ControllerBase
    {
        [HttpPost]
        [Route("PushRecord")]
        public ResponseMessage PushRecord(PushRecord PushRecord)
        {
            ResponseMessage message = new ResponseMessage();
            string ipaddress = GetRequestIPAdress(this.HttpContext.Request);
            bool success = IntelligentGatewayServices.eventRecord(ipaddress, PushRecord);
            if (!success)
            {
                message.errcode = 1;
                message.errmsg = "认证回传出错!";
            }            
            return message;
        }
        [HttpPost]
        [Route("HeartBeat")]
        public ResponseMessage HeartBeat(HeartBeat HeartBeat)
        {
            ResponseMessage message = new ResponseMessage();
            string ipaddress = GetRequestIPAdress(this.HttpContext.Request);
            bool success = PanelDeviceInfoServices.ProcessHeartBeat(HeartBeat.DeviceID,ipaddress);
            if (!success)
            {
                message.errcode = 1;
                message.errmsg = "心跳处理出错!";
            }
            return message;
        }
        private string GetRequestIPAdress(HttpRequest request)
        {
            string ipaddress = request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrEmpty(ipaddress))
            {
                ipaddress = request.HttpContext.Connection.RemoteIpAddress.ToString();
            }
            return ipaddress;
        }
    }
}
